package com.dongliu.controller;

import com.dongliu.domain.Admin;
import com.dongliu.domain.User;
import com.dongliu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private UserService userService;

    @PostMapping
    public Result save(@RequestBody User user) {
        System.out.println(user);
        boolean flag = userService.save(user);
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR, flag);
    }

    @PutMapping
    public Result update(@RequestBody User user) {
        boolean flag = userService.update(user);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR, flag);
    }

    @DeleteMapping("/{username}")
    public Result delete(@PathVariable String username) {
        boolean flag = userService.delete(username);
        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR, flag);
    }

    @GetMapping("/{username}")
    public Result getByUsername(@PathVariable String username) {
        User user = userService.getByUsername(username);
        Integer code = user != null ? Code.GET_OK : Code.GET_ERR;
        String msg = user != null ? "" : "数据查询失败，请重试！";
        return new Result(code, user, msg);
    }

    @GetMapping
    public Result getAll(HttpServletRequest request) {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        if(admin == null)
            return new Result(Code.LOGIN_ERR, null, "请登录后再执行操作！");
        List<User> userList = userService.getAll();
        Integer code = userList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = userList != null ? "":"数据查询失败，请重试！";
        return new Result(code, userList, msg);
    }
}
